package com.redpacketcover.rc.base

import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.util.HashMap

class CommonInterceptor : Interceptor {

    private val mParamsMap = HashMap<String, String>()

    override fun intercept(chain: Interceptor.Chain): Response {
        val oldRequest = chain.request()
        // 新的请求
        val request: Request
        val urlBuilder = oldRequest.url().newBuilder()

        if (mParamsMap.size > 0) {
            for (params in mParamsMap.entries) {
                urlBuilder.addQueryParameter(params.key, params.value)
            }
        }
        request = oldRequest.newBuilder().url(urlBuilder.build()).build()
        return chain.proceed(request)
    }

    class Builder {
        private var mCommonInterceptor: CommonInterceptor =
                CommonInterceptor()

        fun addParams(key: String, value: String): Builder {
            mCommonInterceptor.mParamsMap[key] = value
            return this
        }

        fun addParams(key: String, value: Int): Builder {
            return addParams(key, value.toString())
        }

        fun addParams(key: String, value: Float): Builder {
            return addParams(key, value.toString())
        }

        fun addParams(key: String, value: Long): Builder {
            return addParams(key, value.toString())
        }

        fun addParams(key: String, value: Double): Builder {
            return addParams(key, value.toString())
        }

        fun build(): CommonInterceptor {
            return mCommonInterceptor
        }

    }
}